<?php
namespace app\controller\user;

use think\facade\Db;
use app\BaseController;
use think\facade\Cache;
use think\facade\Env;
use app\common\CommonJwt;
use think\facade\Request;
use think\Model;

class Index extends BaseController{

    /**
     * 项目标识
     */
    private String $mark = "fl";

    private static Int $couponPastDate = 60*10;
    

    public function initialize(){
        $info = Request::header();
        $code = '10001';
        $result = $this->getUIdByToken();
        if ($result == -1) {
            echo json_encode(['code'=>'10003','msg'=>'身份验证失败（无token）']);
            die();
        }else if ($result['code'] == 2) {
            echo json_encode(['code'=>'10004','msg'=>'身份验证失败（token过期）']);
            die();
        }else{
            $uid = $result['data']->uid->id;
            $info['uid'] = $result['data']->uid->id;
        }
    }

    /**
    * 根据openid获取用户信息
    */
    public static function getUiByOpenid($openid){
        // $openid = input('get.openid');
        // $user = Db::name('user')->where('openid',$openid)->field('info_id,id')->find();
        // $infoId = $user['info_id'];
        // $userId = $user['id']
        // $userInfo = Db::name('user_info')->where('id',$infoId)->find();
        $user = Db::name('user')
        ->alias('u')
        ->join('user_info ui','u.info_id=ui.id')
        ->where('openid',$openid)
        ->field('ui.id,ui.nickname as nickName,ui.sex,ui.age,ui.avatar as avatarUrl,ui.city,u.id')->find();
        return $user;
    }


    /**
     * 从token获取user(后端使用)
     */
    public function getUIdByToken(){
        $info = Request::header();
        if (array_key_exists('authorization',$info) != 1 || empty($info['authorization'])) {
            return -1;
        }
        // Cache::store('redis')>get('token_'.$info['authorization'])
        $result = CommonJwt::checkToken($info['authorization']);
        return $result;
    }
    /**
     * 从token获取user(前端接口)
     */
    public function getUserByToken(){
        $info = Request::header();
        if (array_key_exists('authorization',$info) != 1 || empty($info['authorization'])) {
            return BaseController::returnSuccessMsg('10004','身份验证失败（无token）');
        }
        // Cache::store('redis')>get('token_'.$info['authorization'])
        $result = CommonJwt::checkToken($info['authorization']);
        return BaseController::returnSuccessMsg('10001',$result['data']->uid);
        // print_r($result['data']->uid);
    }
    


    /**
     * 更新redis用户信息，token
     */
    public static function updateUiInRedis($params){
        $info = Request::header();
        Cache::store('redis')->del('token_'.$params['openid']);
        // 存储token，用户直接从token获取uid
        Cache::store('redis')->del('token_'.$info['authorization']);
        $token = CommonJwt::signToken($params['user']);
        // print_r($token);
        Cache::store('redis')->set('token_'.$params['openid'],$token,20000);
        return $token;
    }


    /**
     * ！！这里的user_id需要从token获取！！
     * 收藏列表
     */
    public function getCollectsByPage(){
        // 获取请求里面所有数据
        $param = input("get.");
        // 每次请求开始的页面是 页数-1再乘以每页数量
        $start = ($param['start'] - 1)*$param['num'];
        // $uid = $param['uid'];
        // 后端从token获取id
        $uid = ($this->getUIdByToken())['data']->uid->id;
        // 重写上面查询，联表查询,这里的user_id需要从token获取
        $list = Db::name('user_collects')->alias('uc')->join('garden g','uc.garden_id=g.id')->field('g.id,g.img')->where('uc.user_id',$uid)->limit($start,$param['num'])->select()->toArray();
        $total = Db::name('user_collects')->where("user_id",$uid)->count();
        foreach($list as $key=>$value){
            $list[$key]['img'] = explode(",,",$value['img']);
         }
        // $data = Db::name("garden")->limit($start,$param['num'])->select()->toArray();
        // print_r($data);
        $data = ["list"=>$list,"total"=>$total];
        // $result = $this->getUIdByToken();
        return BaseController::returnSuccessMsg('10001',$data);
    }


    /**
     * 预约数量
     */
    public function getYuyueCount(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $status = 1;
        $allMeal = Db::name('user_meal_shopping_chart')
        ->alias('umsc')
        ->join('meals m','umsc.meal_id=m.id')
        ->join('meal_type mt','mt.id=m.meal_type_id')
        ->field('m.money,m.origin,umsc.status,umsc.id,umsc.num')
        ->where(["umsc.user_id"=>$uid,'umsc.status'=>$status])
        ->select();
        // 总数
        $sum = 0;
        // 原总价
        $price = 0;
        // 折扣和总价
        $orPrice = 0;
        foreach($allMeal as $key=>$value){
            $sum += $allMeal[$key]['num'];
            $orPrice += intval($allMeal[$key]['money']) *$allMeal[$key]['num']*($allMeal[$key]['origin']/10);
            $price += intval($allMeal[$key]['money']) *$allMeal[$key]['num'];
         }
        // return BaseController::returnSuccessMsg('10001',['price'=>$price,'orPrice'=>$orPrice,'sum'=>$sum]);
        return ['price'=>$price,'orPrice'=>$orPrice,'sum'=>$sum,'test'=>$allMeal];
    }

    /**
     * 获取用户预约(-1：订单取消，0：订单接受，1：订单准备中，2：订单完成)列表
     */
    public function getYuyueList(){
        $param = input("get.");
        // $uid = $param['uid'];
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $status = $param['status'];
        $start = ($param['start'] - 1)*$param['num'];
        $shoppingChart = Db::name('orders')
        ->alias('umsc')
        ->join('meals m','umsc.meal_id=m.id')
        ->join('meal_type mt','mt.id=m.meal_type_id')
        ->field('m.name,m.img,umsc.date,umsc.money,m.origin,umsc.status,umsc.id,umsc.num,mt.name as type,umsc.meal_id as mid')
        ->where(["umsc.user_id"=>$uid,'umsc.status'=>$status])
        ->limit($start,$param['num'])
        ->order('umsc.date')
        ->select()->toArray();
        
        $total = Db::name('orders')
        ->alias('umsc')
        ->join('meals m','umsc.meal_id=m.id')
        ->join('meal_type mt','mt.id=m.meal_type_id')
        ->field('m.name,m.img,umsc.date,m.money,m.origin,umsc.status,umsc.id,umsc.num,mt.name as type')
        ->where(["umsc.user_id"=>$uid,'umsc.status'=>$status])
        ->count();
        foreach($shoppingChart as $key=>$value){
            $shoppingChart[$key]['img'] = explode(",,",$value['img']);
         }
        return BaseController::returnSuccessMsg('10001',["list"=>$shoppingChart,"total"=>$total]);
    }
    /**
     * 获取购物车(0：从未预约，1：有预约，可叠加)列表
     */
    public function getChartList(){
        $param = input("get.");
        // $uid = $param['uid'];
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $status = $param['status'];
        $start = ($param['start'] - 1)*$param['num'];
        $shoppingChart = Db::name('user_meal_shopping_chart')
        ->alias('umsc')
        ->join('meals m','umsc.meal_id=m.id')
        ->join('meal_type mt','mt.id=m.meal_type_id')
        ->field('m.name,m.img,umsc.date,m.money,m.origin,m.count_sum as count,umsc.status,umsc.id,umsc.num,mt.name as type,umsc.meal_id as mid')
        ->where(["umsc.user_id"=>$uid,'umsc.status'=>$status])
        ->limit($start,$param['num'])
        ->order('umsc.date')
        ->select()->toArray();
        
        $total = Db::name('user_meal_shopping_chart')
        ->alias('umsc')
        ->join('meals m','umsc.meal_id=m.id')
        ->join('meal_type mt','mt.id=m.meal_type_id')
        ->field('m.name,m.img,umsc.date,m.money,m.origin,umsc.status,umsc.id,umsc.num,mt.name as type')
        ->where(["umsc.user_id"=>$uid,'umsc.status'=>$status])
        ->count();
        foreach($shoppingChart as $key=>$value){
            $shoppingChart[$key]['img'] = explode(",,",$value['img']);
         }
        $hasAddress = $this->varityHasAddress($uid);
        return BaseController::returnSuccessMsg('10001',["list"=>$shoppingChart,"total"=>$total,"hasAddress"=>$hasAddress]);
    }

    /**
     * 判断是否有收货地址
     */
    public function varityHasAddress($uid){
        $addresses = Db::name('receiver')
        ->where('user_id',$uid)
        ->select()->toArray();
        $flag = true;
        if (empty($addresses)) {
            $flag = false;
        }
        // return BaseController::returnSuccessMsg('10001',$flag);
        return $flag;
    }
    
    /**
     * 确认订单时在购物车选中的套餐
     */
    public function getOrders(){
        $param = input("get.");
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $addresses = $this->getUserAllReceiver($uid);
        if (empty($addresses)) {
            return BaseController::returnSuccessMsg('10001',['status'=>-1]);
        }
        $status = $param['status'];
        $ids = explode(',',$param['ids']);
        $shoppingChart = Db::name('user_meal_shopping_chart')
        ->alias('umsc')
        ->join('meals m','umsc.meal_id=m.id')
        ->join('meal_type mt','mt.id=m.meal_type_id')
        ->field('m.name,m.img,umsc.date,m.money,m.origin,m.desc,umsc.status,umsc.id,umsc.num,mt.name as type,mt.id as typeid,umsc.meal_id as mid')
        ->where(["umsc.user_id"=>$uid,'umsc.status'=>$status])
        ->where('umsc.id','in',$ids)
        ->select()->toArray();
        $count = 0;
        $total = 0;
        $a = 10;
        foreach($shoppingChart as $key=>$value){
            $shoppingChart[$key]['img'] = explode(",,",$value['img']);
            $count += $shoppingChart[$key]['num'];
            $total += $shoppingChart[$key]['money']*$shoppingChart[$key]['num']*$shoppingChart[$key]['origin']/$a;
         }

        return BaseController::returnSuccessMsg('10001',['status'=>1,'list' => $shoppingChart,'address'=>$addresses,'count' => $count,'total' => $total]);
    }

    /**
     * 购物车内立即预约
     */
    public function completeYuyue(){
        $params = input('post.');
        $id = $params['id'];
        // $uid = $params['uid'];
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $result = Db::name('orders')->where('id','in',$id)->where('user_id',$uid)->update(['status'=>1]);
        $code = '10001';
        $msg = "success";
        if ($result <= 0) {
            $code = '10004';
            $msg = "fail";
        }
        return BaseController::returnSuccessMsg($code,$msg);
    }


    /**
     * 加入预约（购物车）
     */
    public function addYuyue(){
        $code = '10001';
        $params = input('post.');
        $uid = ($this->getUIdByToken())['data']->uid->id;
        // 购物车中间表id
        $midelId = -1;
        if (array_key_exists("midelid",$params)) {
            $midelId = $params['midelid'];
        }
        // 套餐id
        $mId = $params['id'];
        $count = $params['num'];
        $status = 1;
        // 为了在订单详情中区分状态和完成一单还可以继续新增一单，加了条件状态为0（未预约）和1（购物车内未预约）
        $isYuyue = Db::name('user_meal_shopping_chart')
        ->where(['user_id'=>$uid,'meal_id'=>$mId])
        ->where('status','in',[1])
        ->field('id')
        ->find();
        if (!empty($isYuyue) && $midelId != -1) {
            // 已有预约，进行累加
            $result = Db::name('user_meal_shopping_chart')
            ->where('id',$midelId)
            ->update(['num'=>$count]);
            $yuyueCount = $this->getYuyueCount();
            return BaseController::returnSuccessMsg($code,['status'=>$result,'amount'=>$yuyueCount]);
        }else{
            $chartData = ['user_id'=>$uid,'meal_id'=>$mId,'status'=>$status,'num'=>1,'date'=>date("Y-m-d H:i")];
            $result = Db::name('user_meal_shopping_chart')->insertGetId($chartData);
            $status = 1;
            if (!$result) {
                $code = '10004';
                $status = 0;
            }
            $yuyueCount = $this->getYuyueCount();
        }
        return BaseController::returnSuccessMsg($code,['status'=>$status,'id'=>$result,'amount'=>$yuyueCount]);
    }

    /**
     * 删除预约
     */
    public function delYuyue(){
        $mids = input("post.mids");
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $result = Db::name("user_meal_shopping_chart")
        ->delete($mids);
        $yuyueCount = $this->getYuyueCount();
        if ($result > 0) {
            $code = '10001'; 
            $data = "success";
        }else{
            $code = '10004';
            $data = "fail";
        }
        return BaseController::returnSuccessMsg($code,["msg"=>$data,'amount'=>$yuyueCount]);
    }


    /**
     * 获取用户财产金额，优惠券数量，消息数量
     */
    public function getMeans(){
        // $uid = input('get.uid');
        $uid = ($this->getUIdByToken())['data']->uid->id;
        // 余额查询
        $nowDate = time();
        $balance = Db::name('means')->where('user_id',$uid)->field('balance')->find();
        // 优惠券数量查询
        $coupon = Db::name('coupon')
        ->alias('c')
        ->join('user_coupon uc','c.id=uc.coupon_id')
        ->join('user u','u.id=uc.user_id')
        ->where(['uc.user_id'=>$uid,'uc.status'=>0])
        ->whereTime('c.end_date','>',$nowDate)
        ->count();
        // 消息数量查询(目前有：优惠券过期提醒消息和物流到店提醒)
        $couponMsg = $this->getCouponMessages($uid);
        $logisticsMsg = $this->getLogisticsMessages($uid);
        $message = $couponMsg['count'] + $logisticsMsg['count'];
        $data = ["balance"=>$balance['balance'],"coupon"=>$coupon,"message"=>$message,"messageItem"=>['coupon'=>$couponMsg['count'],'logistics'=>$logisticsMsg['count']]];
        return BaseController::returnSuccessMsg('10001',$data);
    }


    /**
     * 获取购物券列表
     */
    public function getCoupons(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        // 当前时间戳
        $nowDate = time();
        // 已有优惠券,且未被使用
        $myCoupons = Db::name('coupon')
        ->alias('c')
        ->join('user_coupon uc','uc.coupon_id=c.id')
        ->where(['uc.user_id'=>$uid,'uc.status'=>0])
        ->whereTime('c.end_date','>',$nowDate)
        ->field('c.id,c.name,c.price,c.limit_price as limitPrice,c.limit_meal as limitMeal,c.start_date as startDate,c.end_date as endDate,c.status')
        ->select()->toArray();
        // 未领取优惠券id的sql
        $myCouponIds = Db::name('coupon')
        ->alias('c')
        ->field('c.id')
        ->join('user_coupon uc','uc.coupon_id=c.id')
        ->where('uc.user_id',$uid)
        // ->column('c.id');
        ->buildSql();
        // 未领取优惠券查询
        $canGetCoupons = Db::name('coupon')
        ->alias('c')
        ->field('c.id,c.name,c.price,c.limit_price as limitPrice,c.limit_meal as limitMeal,c.start_date as startDate,c.end_date as endDate,c.status')
        ->where('c.id not in'.$myCouponIds)
        ->whereTime('c.end_date','>',$nowDate)
        ->select()->toArray();
        $type = Db::name('meal_type')->field('id,name')->select()->toArray();
        foreach($myCoupons as $key=>$value){
            if ($value['limitMeal'] == 0) {
                $myCoupons[$key]['limitMeal'] = "通用优惠券";
                $myCoupons[$key]['type'] = "0";
                $myCoupons[$key]['startDate'] = date('Y-m-s h:i:s',$value['startDate']);
            }else{
                $myCoupons[$key]['type'] = "1";
                $myCoupons[$key]['limitMeal'] = $type[$key]['name'];
            }
            $myCoupons[$key]['endDate'] = date('Y-m-d',$value['endDate']);
            $myCoupons[$key]['startDate'] = date('Y-m-d',$value['startDate']);
         }
        foreach($canGetCoupons as $key=>$value){
            if ($value['limitMeal'] == 0) {
                $canGetCoupons[$key]['limitMeal'] = "通用优惠券";
                $canGetCoupons[$key]['type'] = "0";
            }else{
                $canGetCoupons[$key]['type'] = "1";
                $canGetCoupons[$key]['limitMeal'] = $type[$key]['name'];
            }
            $canGetCoupons[$key]['endDate'] = date('Y-m-d',$value['endDate']);
            $canGetCoupons[$key]['startDate'] = date('Y-m-d',$value['startDate']);
         }
        return BaseController::returnSuccessMsg('10001',['myCoupons'=>$myCoupons,'canGetCoupons'=>$canGetCoupons]);
    }


    /**
     * 优惠券领取
     */
    public function userGetCoupon(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $id = input('post.id');
        $insert = ['user_id'=>$uid,'coupon_id'=>$id,'status'=>0];
        $result = Db::name('user_coupon')->insert($insert);
        if ($result == 1) {
            return $this->getCoupons();
        }
        return BaseController::returnSuccessMsg('10002','领取失败');
    }


    /**
    * 获取单个套餐信息（-1，未预约。0，购物车内，1，预约未付尾款，2，订单完成）
    */
    public function getMealDetail(){
        $mId = input('get.mid');
        $uId = ($this->getUIdByToken())['data']->uid->id;
        $meal = Db::name('meals')
        ->alias('m')
        ->join('meal_type mt','m.meal_type_id=mt.id')
        ->field('m.id,m.name,m.desc,m.like,m.img,m.recom,m.money,mt.name as type,mt.rank,m.origin,m.origin_date as originDate,m.count_sum as SumCount,m.count_residue as ResidueCount')
        ->where("m.id",$mId)->find();
        if (array_key_exists('img',$meal)) {
            $meal['img'] = explode(",,",$meal['img']);
        }
        // 返回折扣剩余天数
        if (array_key_exists('originDate',$meal)) {
            $nowDate = strtotime(date('Y-m-d H:i:s'));
            $endDate = $meal['originDate'];
            $getSecs = ($endDate - $nowDate)*1000;
            $meal['originDate'] = $getSecs;
        }
        // 为了在订单详情中区分状态和完成一单还可以继续新增一单，加了条件状态为0（未预约）和1（购物车内未预约）
        $yuyueResult = Db::name('user_meal_shopping_chart')
        ->alias('um')
        ->join('meals m','m.id=um.meal_id')
        ->field('um.id,um.status,um.num')
        ->where(['um.user_id'=>$uId,'m.id'=>$mId,])
        ->where('um.status','in',[1])
        ->select()->toArray();
        // $hasYuyue = false;
        if (empty($yuyueResult)) {
            $yuyueResult[0]['status'] = false;
        }else{
            $yuyueResult[0]['status'] = true;
        }
        $yuyueCount = $this->getYuyueCount();
        $tips = new \app\controller\other\Index($this->app);
        $tip = $tips->getTip();
        // return json($yuyueResult);
        return BaseController::returnSuccessMsg('10001',['list'=>$meal,'yuyueStatus'=>$yuyueResult,'amount'=>$yuyueCount,'tip'=>$tip]);
    }


    /**
     * 获取订单中套餐信息
     */
    public function getMealOrder(){
        $id = input("get.id");
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $order = Db::name("orders")
        ->alias('umsc')
        ->join("receiver r","umsc.receiver_id=r.id")
        ->join("meals m","m.id = umsc.meal_id")
        ->join("meal_type mt","mt.id=m.meal_type_id")
        ->where(["umsc.id"=>$id,"umsc.user_id"=>$uid])
        ->field("m.name as title,m.img,m.desc,m.money,m.origin,mt.name as type,r.name,r.name,r.tel,r.address,r.message,umsc.id as mid,umsc.meal_id as id,umsc.date,umsc.num,umsc.money as paidMoney,umsc.status")
        ->find();
        if ($order && array_key_exists('img',$order)) {
            $order['img'] = explode(",,",$order['img']);
        }
        $logistics = Db::name("logistics")
        ->field('name,status,date')
        ->where('order_id',$id)
        ->find();
        if ($logistics && !empty($logistics)) {
            $logistics['date'] = date('m-s h:i',$logistics['date']);
        }
        $tips = new \app\controller\other\Index($this->app);
        $tip = $tips->getTip();
        return BaseController::returnSuccessMsg("10001",['order'=>$order,'tip'=>$tip,'logistics'=>$logistics]);
        // print_r($order['img']);
    }

    /**
     * 改变预约订单的状态
     */
    public function changeOrderStatus(){
        $params = input("post.");
        $id = $params["id"];
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $status = $params["status"];
        $result = Db::name("orders")->where('id',$id)->update(['status'=>$status]);
        $msg = ["status"=>'success',"msg"=>"操作成功"];
        if ($result != 1) {
            $msg = ["status"=>'none',"msg"=>"操作失败"];
        }else{
            if (array_key_exists("type",$params)) {
                $insert = ["remarks"=>$params['recomand'],"type"=>$params["type"],"umsc_id"=>$id];
                Db::name("feedback_meal")->where("umsc_id",$id)->insert($insert);
            }
        }
        return BaseController::returnSuccessMsg("10001",$msg);
    }

    /**
     * 收藏(取消)花
     */
   public function collectFlower(){
       $params = input('post.');
       $fid = $params['fid'];
    //    $uid = $params['uid'];
        $uid = ($this->getUIdByToken())['data']->uid->id;
       $hasCollect = Db::name('user_collects')->where(['user_id'=>$uid,'garden_id'=>$fid])->find();
       $msg;
       if ($hasCollect && array_key_exists('id',$hasCollect)) {
           $msg = Db::name('user_collects')->delete($hasCollect['id']);
       }else{
           $insert = ["user_id"=>$uid,"garden_id"=>$fid];
           $msg = Db::name('user_collects')->insert($insert);
       }
    return BaseController::returnSuccessMsg("10001",$msg);
   }

   /**
    * 公共方法，请求用户所有地址
    */
   public function getUserAllReceiver($uid){
    $data = Db::name('receiver')->where('user_id',$uid)->order('default desc')->select()->all();
    foreach($data as $key=>$value){
        $data[$key]['gender'] = ($value['gender'] == 1 || $value['gender'] == "1") ? '男' : '女';
        $data[$key]['tags'] = ($value['tags'] == "0") ? '其他' : ($value['tags'] == "1" ? "家" : "公司");
        $data[$key]['default'] = ($value['default'] == "0") ? false : true;
     }
     return $data;
   }

   /**
    * 查询所有收货地址
    */
    public function loadAllReceiver(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $data = $this->getUserAllReceiver($uid);
        $tips = new \app\controller\other\Index($this->app);
        $tip = $tips->getTip();
        return BaseController::returnSuccessMsg("10001",['list'=>$data,'tip'=>$tip]);
    }

    /**
     * 修改默认收货地址（修改成功，重新查询并排序收货地址返回）
     */
    public function changeDefaultReceiver(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $id = input('post.id');
        $preDefaultId = Db::name('receiver')->where('default',"1")->field('id')->find();
        $result1 = 0;
        $result2 = 0;
        if ($preDefaultId['id']."" == $id."") {
            return;
        }
        if (array_key_exists('id',$preDefaultId)) {
            $result1 = Db::name('receiver')->where(['user_id'=>$uid,'id'=>$preDefaultId['id']])->update(['default'=>"0"]);
        }
        if ($result1 == 1) {
            $result2 = Db::name('receiver')->where(['user_id'=>$uid,'id'=>$id])->update(['default'=>"1"]);
        }
        if ($result2 == 1) {
            return $this->loadAllReceiver();
        }
        return BaseController::returnSuccessMsg("10001",'修改失败');
    }


    /**
     * 删除收货地址
     */
    public function delReceiver(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $id = input('post.id');
        $preDefaultId = Db::name('receiver')->where('default',"1")->field('id')->find();
        if ($preDefaultId['id']."" == $id."") {
            return;
        }
        $result = Db::name('receiver')->where(["user_id"=>$uid,'id'=>$id])->delete();
        if ($result == 1) {
            return $this->loadAllReceiver();
        }else{
            return BaseController::returnSuccessMsg("10001",'删除失败');
        }
    }

   /**
    * 新增收货地址(最多6个)
    */
    public function insertReceiver(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $count = Db::name('receiver')->where('user_id',$uid)->count();
        if ($count >= 6) {
           return BaseController::returnSuccessMsg("10001","目前收货地址最多支持设置6个");
        }
        $params = input('post.');
        $insert = ['user_id'=>$uid,'name'=>$params['name'],'gender'=>$params['gender'],'tel'=>$params['tel'],'address'=>$params['address'],'tags'=>$params['tags'],'default'=>$params['isDefault']];
        $reasult = Db::name('receiver')->where('user_id',$uid)->insertGetId($insert);
        if ($params['isDefault'].'' == '1') {
            $preDefaultId = Db::name('receiver')->where('default',"1")->field('id')->find();
            $result1 = 0;
            if (array_key_exists('id',$preDefaultId)) {
                $result1 = Db::name('receiver')->where(['user_id'=>$uid,'id'=>$preDefaultId['id']])->update(['default'=>"0"]);
            }
            if ($result1 != 1) {
                Db::name('receiver')->where('id',$reasult)->delete();
            }
        }
        $code = 1;
        if ($reasult == 0) {
            $code = 0;
        }
        return BaseController::returnSuccessMsg("10001",$code);
    }

    /**
     * 选择切换优惠券(redis缓存，二维数组)
     */
    public function checkCoupon(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $params = input('get.');
        $couponCache = Cache::store('redis')
        ->get('coupon_'.$uid);
        $couponCache[$params['typeid']][$params['mid']] = $params;
        Cache::store('redis')
        ->set('coupon_'.$uid,$couponCache,Self::$couponPastDate);
        
        $couponCache = Cache::store('redis')
        ->get('coupon_'.$uid);

        $couponids = [];
        foreach($couponCache as $k=>$v){
            foreach($v as $k=>$value){
                array_push($couponids,$value['midleid']);
            }
        }
        // 获取优惠总价
        $coupons = Db::name('coupon')
        ->alias('c')
        ->join('user_coupon uc','c.id = uc.coupon_id')
        ->where('uc.id','in',$couponids)
        ->field('c.price')
        ->select()->toArray();
        $data = array_reduce($coupons,function($t,$c){
            return $t + $c['price'];
        },0);
        return BaseController::returnSuccessMsg("10001",$data);
    }

    /**
    * 点击套餐选择用户可用的优惠券
    * 条件：用户，优惠券有效时间，限制的套餐类型(包含通用型0)
    */
    public function getUserCouponByMeal(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $params = input('get.');
        // 第一步：从缓存取出用户使用中的所有优惠券
        $couponCache = Cache::store('redis')
        ->get('coupon_'.$uid);
        // 第二部：根据套餐的id和套餐类型的id得到指定套餐可以使用的优惠券中被使用中的优惠券
        $cacheDatas = [];
        $filterActiveDatas= [];
        $filedType = $params['typeid'];
        $filedMid = $params['mid'];
        $filedChartid = $params['chartid'];
        $thisChartData = Db::name('user_meal_shopping_chart')
        ->alias('umsc')
        ->join('meals m','m.id=umsc.meal_id')
        ->where(['user_id'=>$uid,'meal_id'=>$filedMid])
        ->field('m.money,m.origin,umsc.num')
        ->find();
        $thisMoney = $thisChartData['money']*($thisChartData['origin']/10)*$thisChartData['num'];
        // 当前时间戳
        $nowDate = time();
        if ($couponCache) {
            foreach($couponCache as $k=>$v){
                foreach($v as $k1=>$v1){
                    // 筛选已使用的限制套餐的优惠券
                    if ($k == $filedType) {
                    // 选出已经被其他套餐使用的优惠券，并且需要加载本套餐使用中的优惠券
                        if (($v[$v1['mid']]['typeid'] == $filedType && $v[$v1['mid']]['mid'] != $filedMid)) {
                            array_push($cacheDatas,$v[$v1['mid']]['midleid']);
                        }
                        if ($v[$v1['mid']]['typeid'] == $filedType) {
                            array_push($filterActiveDatas,$v[$v1['mid']]['midleid']);
                        }
                    }
                    // 筛选已使用的通用优惠券
                    if($v[$v1['mid']]['typeid'] != $filedType 
                    && ($v[$v1['mid']]['limitmeal'] == "0" || $v[$v1['mid']]['limitmeal'] == 0)){
                        array_push($cacheDatas,$v[$v1['mid']]['midleid']);
                    }
                }
             }
        }
        // 已被选中的优惠券（需要在查询中进行排除，防止优惠券重复使用）
        $data = Db::name('coupon')
        ->alias('c')
        ->join('user_coupon uc','uc.coupon_id=c.id')
        ->join('meals m','c.limit_meal=m.meal_type_id or c.limit_meal=0')
        ->where(['uc.user_id'=>$uid,'m.id'=>$params['mid']])
        ->where('uc.id','not in',$cacheDatas)
        ->where('uc.status',0)
        ->where('c.limit_price','<=',$thisMoney)
        ->whereTime('c.end_date','>',$nowDate)
        ->field('c.id,c.name,uc.id as midleId,m.id as mid,m.meal_type_id as typeid,c.price,c.status,c.end_date as endDate,c.start_date as startDate,c.limit_price as limitPrice,c.limit_meal as limitMeal')
        ->select()->toArray();
        foreach($data as $k=>$v){
            if (in_array($v['midleId'],$filterActiveDatas)) {
                $data[$k]['active'] = true;
            }else{
                $data[$k]['active'] = false;
            }
            $data[$k]['endDate'] = date('m-d',$v['endDate']);
            $data[$k]['startDate'] = date('m-d',$v['startDate']);
        }
        return BaseController::returnSuccessMsg("10001",$data);
    }

    /**
     * 未提交还原优惠券状态
     */
    public function restoreCouponStatus(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $result = Cache::store('redis')->del('coupon_'.$uid);
        return BaseController::returnSuccessMsg("10001",$result);
    }

    /**
     * 改变优惠券状态
     * $uid:用户id
     * $couponids:优惠券id
     * $status:优惠券需要改变的状态
     */
    public function changeCouponStus($couponids,$uid,$status){
        $result = Db::name('user_coupon')
        ->where('user_id',$uid)
        ->where('id','in',$couponids)
        ->update(['status'=>$status]);
        // ->select()->toArray();
        $data = 0;
        if (count($couponids) == $result) {
            $data = 1;
        }
        // return ['couponids'=>$couponids,'uid'=>$uid,'status'=>$status];
        return $data;
    }

    /**
     * 从redis查询所有订单中的优惠券id
     */
    public function getRedisCoupon($uid){
        $couponCacheDatas = Cache::store('redis')->get('coupon_'.$uid);
        $couponIds = [];
        if (!empty($couponCacheDatas)) {
            foreach ($couponCacheDatas as $key => $value) {
                foreach ($value as $k => $v) {
                    array_push($couponIds,$v['midleid']);
                }
            }
        }

        return $couponIds;
    }

    /**
     * 下单并确认收货地址，一个或多个订单共享一个收货地址
     */
    public function changeOrderAddress(){
        $params = input('post.');
        $ids = explode(',',$params['ids']);
        $receiver = $params['receiverid'];
        // 参数：每单支付金额保留
        $orderResult = json_decode($params['orderresult'],true);
        // return $orderResult;
        $nowDate = time();
        $uid = ($this->getUIdByToken())['data']->uid->id;
        // 1.从购物车中查出需要预约的套餐的信息
        $chartList = Db::name('user_meal_shopping_chart')
        ->where("id","in",$ids)
        ->field('user_id,meal_id,status,date,num,id')
        ->select()->toArray();
        $checkMealIds = [];
        if (!empty($chartList)) {
            foreach ($chartList as $key => $value) {
                array_push($checkMealIds,$value['meal_id']);
            }
        }
        // 查询个人剩余积分
        $myIntegral = Db::name('means')
            ->where('user_id',$uid)
            ->field('balance')
            ->find();
        // 物流列表
        $logisticsList = [];
        // 完成订单获得剩余积分
        $updatedIntegral = 0;
        // return ["t1"=>$chartList,"t2"=>$orderResult];
        foreach ($chartList as $key => $value) {
            $chartList[$key]['date'] = date('y-m-s h:i',$nowDate);
            $chartList[$key]['status'] = 0;
            $chartList[$key]['receiver_id'] = $receiver;
            $logisticsList[$key]['name'] = "备货中";
            $logisticsList[$key]['status'] = -1;
            $logisticsList[$key]['date'] = time();
            foreach ($orderResult as $k => $v) {
                if ($v['midleid'] == $value['id']) {
                    $chartList[$key]['money'] = $v['money'];
                    $chartList[$key]['coupon_id'] = $v['couponid'];
                    $logisticsList[$key]['order_id'] = $v['midleid'];
                } 
            }
            // 查找当前遍历到的套餐的数量
            $sum = Db::name('meals')
            ->where('id',$value['meal_id'])
            ->field('count_residue,origin,money')
            ->find();
            // 下单成功，减少对应套餐的总数
            Db::name('meals')
            ->where('id',$value['meal_id'])
            ->update(['count_residue'=>($sum['count_residue']-$value['num'])]);
            // 每单的获取积分是支付价格的 1/10，购物车结账获得30%的积分，完成订单再获得剩余的70%的积分
            $updatedIntegral += (($value['num']*$sum['money']*$sum['origin']/10)*3/10)/10;
        }
        // 2.将信息转储到订单表并绑定时间和收货地址
        $result = Db::name('orders')
        ->insertAll($chartList);
        $data = 0;
        $result1 = 0;
        if ($result == count($ids)) {
            // 初始化物流信息
            Db::name('logistics')
            ->insertAll($logisticsList);
            $data = 1;
            Db::name('means')
            ->where('user_id',$uid)
            ->update(['balance'=>$myIntegral['balance']+$updatedIntegral]);
            // 3.删除购物车中已成功预约的套餐
            $chartList = Db::name('user_meal_shopping_chart')
            ->where("id","in",$ids)
            ->delete();
            // 从redis查询所有订单中的优惠券id
            $couponIds = $this->getRedisCoupon($uid);
            $result1 = $this->changeCouponStus($couponIds,$uid,1);
            Cache::store('redis')->del('coupon_'.$uid);
            if($result1 != 1){
                $this->restoreCouponStatus();
            }
        }
        return $result1;
    }


    /**
     * 结算尾款，更新物流
     */
    public function updateLogitisc($id){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        Db::name('logistics')
        ->where('order_id',$id)
        ->update(['status'=>2,'date'=>time()]);
    }



    /**
     * 提交订单
     */
    public function commitChart(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $result = $this->changeOrderAddress();
        return BaseController::returnSuccessMsg("10001",$result);
    }


    /**
     * 加载消息列表（未分类）
     * 目前有：优惠券过期提醒(提前一天)，物流到店提醒(0)
     */
    public function loadMessages(){
        $type = input('get.type');
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $data = [];
        switch ($type) {
            case 'coupon':
                $data = $this->getCouponMessages($uid);
                break;
            case 'logistics':
                $data = $this->getLogisticsMessages($uid);
                break;
            
            default:
                # code...
                break;
        }
        return BaseController::returnSuccessMsg("10001",$data['data']);
    }

    /**
     * 获取优惠券过期提醒信息列表(提前一天)
     */
    public function getCouponMessages($uid){
        $unixNum = 86400;
        $nowDate = time();
        $coupons = Db::name('coupon')
        ->alias('c')
        ->join('user_coupon uc','uc.coupon_id=c.id')
        ->whereTime('c.end_date','<=',$nowDate - $unixNum)
        ->where(['uc.status'=>0,'uc.user_id'=>$uid])
        ->field('c.name')
        ->select()->toArray();
        $count = Db::name('coupon')
        ->alias('c')
        ->join('user_coupon uc','uc.coupon_id=c.id')
        ->whereTime('c.end_date','<=',$nowDate - $unixNum)
        ->where(['uc.status'=>0,'uc.user_id'=>$uid])
        ->count();
        foreach ($coupons as $k => $v) {
            $coupons[$k]['date'] = date('m-s h:i',$nowDate);
            $coupons[$k]['desc'] = "您的优惠券即将过期";
        }
        return ['data'=>$coupons,'count'=>$count];
    }

    /**
    * 获取物流到店提醒信息列表
    */
    public function getLogisticsMessages($uid){
        $logistics = Db::name('logistics')
        ->alias('l')
        ->join('orders umsc','umsc.id=l.order_id')
        ->join('meals m','m.id=umsc.meal_id')
        ->join('message me','me.path_id=umsc.id')
        ->where(['umsc.user_id'=>$uid,'l.status'=>1,'me.attention'=>0])
        ->field('m.name,l.date')
        ->select()
        ->toArray();
        $count = Db::name('logistics')
        ->alias('l')
        ->join('orders umsc','umsc.id=l.order_id')
        ->join('meals m','m.id=umsc.meal_id')
        ->join('message me','me.path_id=umsc.id')
        ->where(['umsc.user_id'=>$uid,'l.status'=>1,'me.attention'=>0])
        ->count();

        foreach ($logistics as $k => $v) {
            $logistics[$k]['date'] = date('m-s h:i',$v['date']);
            $logistics[$k]['desc'] = "您有到店订单未完成";
        }
        return ['data'=>$logistics,'count'=>$count];
    }

    /**
     * 物流消息已读
     */
    public function clearNewMessages(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        Db::name('message')
        ->alias('m')
        ->join('orders umsc','umsc.id = m.path_id')
        ->where('umsc.user_id',$uid)
        ->update(['m.attention'=>1]);
        return BaseController::returnSuccessMsg("10001",'操作成功');
    }


    /**
     * 完成订单
     * tips:不能删除完成订单优惠券，因为删除以后，在个人中心便可以查看到此优惠券又可以领取。
     * 删除时需要后台管理系统章下架优惠券时进行同步删除，这里将优惠券状态改为2即可
     */
    public function completeOrder(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $params = input('post.');
        $result;
        $orderCoupon = Db::name('orders')
        ->where('id',$params['midleid'])
        ->field('coupon_id,meal_id,num')
        ->find();
        if ($orderCoupon && !empty($orderCoupon) && $orderCoupon['coupon_id'] != 0) {
            $result = Db::name('orders')
            ->alias('o')
            ->join('user_coupon uc','uc.coupon_id=o.coupon_id')
            ->where(['o.user_id'=>$uid,'o.id'=>$params['midleid']])
            ->update(['o.status'=>2,'uc.status'=>2]);
        }else{
            $result = Db::name('orders')
            ->where(['user_id'=>$uid,'id'=>$params['midleid']])
            ->update(['status'=>2]);
        }
        // 查询对应套餐的价格折扣用以计算获得的积分
        $meal = Db::name('meals')
        ->where('id',$orderCoupon['meal_id'])
        ->field('money,origin')
        ->find();
        $this->updateLogitisc($params['midleid']);
        // 个人总积分
        $myIntegral = Db::name('means')
        ->where('user_id',$uid)
        ->field('balance')
        ->find();
        $canGetIntegral = $myIntegral['balance'] + ($meal['money']*($meal['origin']/10)*$orderCoupon['num'])*(7/10)/10;
        // 获取积分
        Db::name('means')
        ->where('user_id',$uid)
        ->update(['balance'=>$canGetIntegral]);
        $flag = 1;
        if ($result <= 0) {
            $flag = 0;
        }
        return BaseController::returnSuccessMsg("10001",$flag);
        

    }

    /**
     * 兑换积分物品
     */
    public function commitIntegralOrder(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $params = input('post.');
        // 查询个人积分
        $myIntegral = Db::name('means')
        ->where('user_id',$uid)
        ->field('balance,status')
        ->find();
        $interal = Db::name('integral')
        ->where('id',$params['id'])
        ->field('name,integral,count')
        ->find();
        
        if ($interal['count'] <= 0) {
            return BaseController::returnSuccessMsg("10001",['status'=>0,'msg'=>'商品已售空','icon'=>'none']);
        }
        else if ($interal && !empty($interal) && $myIntegral['status'] == 1) {
            // print_r("进入这里0");
            if ($interal['integral'] > $myIntegral['balance']) {
                // print_r("进入这里1");
                return BaseController::returnSuccessMsg("10001",['status'=>-1,'msg'=>'您的积分不够','icon'=>'none']);
            }else{
                // print_r("进入这里2");
                $insert = ['name'=>$interal['name'],'date'=>time(),'integral_id'=>$params['id'],'status'=>0,'user_id'=>$uid];
                $result = Db::name('integral_orders')
                ->insert($insert);
                if ($result == 1) {
                    // 个人积分减少对应数量
                    Db::name('means')
                    ->where('user_id',$uid)
                    ->update(['balance'=>$myIntegral['balance']-$interal['integral']]);
                    // 积分商城对应商品减少数目
                    Db::name('integral')
                    ->where('id',$params['id'])
                    ->update(['count'=>($interal['count']-1)]);
                    // 返回减少后的商品列表
                    $start = ($params['start'] - 1)*$params['num'];
                    $count = Db::name('integral')
                    ->count();
                    $list = Db::name('integral')
                    ->limit($start,$params['num'])
                    ->select();
                }
                return BaseController::returnSuccessMsg("10001",['status'=>1,'msg'=>'兑换成功','data'=>['list'=>$list,'balance'=>$myIntegral['balance']-$interal['integral']],'icon'=>'success']);
            }
        }
        
    }
    

    /**
     * 获取积分订单
     */
    public function getIntegralOrder(){
        $uid = ($this->getUIdByToken())['data']->uid->id;
        $params = input('get.');
        $start = ($params['start'] - 1)*$params['num'];
        $count = Db::name('integral_orders')
        ->where('user_id',$uid)
        ->count();
        if ($start*$params['num'] >= $count) {
            return BaseController::returnSuccessMsg('10001',-1);
        }
        $list = Db::name('integral_orders')
        ->alias('io')
        ->join('integral i','io.integral_id = i.id')
        ->where('user_id',$uid)
        ->limit($start,$params['num'])
        ->field('io.name,io.date,i.img,i.integral,io.status')
        ->order('date','asc')
        ->select()->toArray();
        foreach ($list as $key => $value) {
            $list[$key]['date'] = date('m-s h:i',$value['date']);
        }
        return BaseController::returnSuccessMsg('10001',['list'=>$list,'total'=>$count]);
    }



}




?>